package com.xoa.plugin;

import com.alibaba.fastjson.JSONArray;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dev.jinOuWorkFlowWebService.localhost.services.DocService.DocServiceLocator;
import com.xoa.dev.jinOuWorkFlowWebService.localhost.services.DocService.DocServicePortType;
import com.xoa.dev.jinOuWorkFlowWebService.util.GdPara;
import com.xoa.dev.jinOuWorkFlowWebService.util.LoadConfig;
import com.xoa.dev.jinOuWorkFlowWebService.weaver.docs.webservices.DocAttachment;
import com.xoa.dev.jinOuWorkFlowWebService.weaver.docs.webservices.DocInfo;
import com.xoa.dev.jinOuWorkFlowWebService.webservices.IncomingServiceLocator;
import com.xoa.dev.jinOuWorkFlowWebService.webservices.IncomingServicePortType;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.WFE.WFERunner.WFERunner;
import com.xoa.util.DateFormat;
import com.xoa.util.FileUploadUtil;
import com.xoa.util.common.StringUtils;
import org.apache.axis.encoding.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.rpc.ServiceException;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;


@Service
public class WorkFlowPushTrigger implements TriggerSubject {

    //公司标识
    private String conpanyFlag = "17";

    @Resource
    private WFERunner wfeRunner;
    @Autowired
    private WorkMapper workMapper;

    @Override
    public void doRun(String company, Object... ags) {
        try {
            LoadConfig.initConfig();
//            System.out.println(GdPara.url);
//            System.out.println("插件开始");
            TriggerPlugIn tri = (TriggerPlugIn) ags[0];
            //System.out.println("1111111111111111111111");
            //查找公共附件，如果有附件需要先调用泛微上传接口获得附件ID拼在推送数据json中
            if (StringUtils.checkNull(company)) {
                company = "xoa1001";
            }
            List<Attachment> attachments = wfeRunner.getWfeFlowRunInfo().findworkUpload(tri.getRunId(), company).getObj();
            StringBuffer fj = new StringBuffer();
            StringBuffer zw = new StringBuffer();
            if (attachments.size() > 0) {
                //控制正文只能有一个
                boolean flag = true;
                for (Attachment attachment : attachments) {
                     StringBuilder uploadHead = FileUploadUtil.getUploadHead();
                     uploadHead.append(System.getProperty("file.separator")).
                            append(company).append(System.getProperty("file.separator")).
                            append("workflow").append(System.getProperty("file.separator")).
                            append(attachment.getYm()).append(System.getProperty("file.separator")).
                            append(attachment.getAttachId()+"."+attachment.getAttachName());

                    //System.out.println(uploadHead.toString());
                    int docId = crateDoc(uploadHead.toString(), attachment.getAttachName());
                    if(flag && attachment.getAttachName().indexOf("[正文]") != -1){
                        flag = false;
                        zw.append(docId);
                    }else {
                        fj.append(docId).append(",");
                    }
                }
            }
            String dto = onversioncDto(tri.getModify(), fj,zw,
                    tri.getFlowId(),
                    tri.getRunId(),
                    tri.getRunName(),
                    tri.getPrcsId(),
                    tri.getFlowPrcs());

            IncomingServiceLocator incomingServiceLocator = new IncomingServiceLocator();
            IncomingServicePortType incomingServicePortType = incomingServiceLocator.getIncomingServiceHttpPort();
            String result = incomingServicePortType.incoming(dto,conpanyFlag);
            //根据返回结果将集团收文状态回显表单
            if(result.indexOf("TRUE") == -1){
                //推送失败
                result = "光大集团未接收";
            }else {
                //推送成功
                result = "光大集团已接收";
            }
            //用来存储sql传入参数
            Map<String, Object> param = new HashMap();
            List<String> key = new ArrayList<String>();
            String tableName = "flow_data_" + tri.getFlowId();
            key.add(GdPara.field+"='"+result+"'");
            param.put("tableName", tableName);
            param.put("keys", key);
            param.put("runId", String.valueOf(tri.getRunId()));
            workMapper.update(param);
            System.out.println("===:"+result);
        }catch (Exception e){
            e.printStackTrace();
        }
        //initWebService(formdata,conpanyFlag);
    }




    //{"急缓":"DATA_35",
    // "核稿人":"DATA_25",
    // "电话":"DATA_20",
    // "印数":"DATA_31",
    // "备注":"DATA_48",
    // "发文编号":"DATA_36",
    // "日期":"DATA_30",
    // "董事长签字":"DATA_62",
    // "董事长审批意见":"DATA_61",
    // "主办部门":"DATA_28",
    // "总经理签字":"DATA_59",
    // "签发人":"DATA_26",
    // "总经理审批意见":"DATA_58",
    // "综合管理部审核签字":"DATA_66",
    // "部门审核意见":"DATA_63",
    // "综合管理部审核意见":"DATA_65",
    // "综合管理部核签":"DATA_47",
    // "密级":"DATA_32",
    // "部门审核":"DATA_41",
    // "综合管理部核签意见":"DATA_67",
    // "主送":"DATA_38",
    // "董事长审批":"DATA_56",
    // "抄送":"DATA_39",
    // "综合管理部核签签字":"DATA_68",
    // "会签部门":"DATA_37",
    // "呈送":"DATA_4",
    // "部门签发":"DATA_42",
    // "部门会签意见":"DATA_44",
    // "综合管理部审核":"DATA_45",
    // "拟稿人":"DATA_15",
    // "部门签字":"DATA_64",
    // "总经理审批":"DATA_53",
    // "标题":"DATA_2"}

    public String onversioncDto(String formdata,StringBuffer fj,StringBuffer zw,String flowId,String runId,String runName,String prcsId,String flowPrcs){
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        //如果存在附件
        jsonObject.put("fj",""); //附件
        jsonObject.put("zw",""); //正文
        if(!StringUtils.checkNull(fj.toString())){
            jsonObject.put("fj",fj.toString().substring(0,fj.length()-1)); //附件
        }
        if(!StringUtils.checkNull(zw.toString())){
            jsonObject.put("zw",zw.toString()); //正文
        }
        List<Map<String, Object>> data = JSONArray.parseObject(formdata, List.class);
        jsonObject.put("gsbs",conpanyFlag); //公司标识
        jsonObject.put("sfxyfh","N");//是否需要返回
        jsonObject.put("zrz","光大金瓯");
        jsonObject.put("zrzlsh",runId);
        jsonObject.put("bgtyj",""); //办公厅意见
        jsonObject.put("mj",""); //密级
        jsonObject.put("jh",""); //急缓
        jsonObject.put("sh",""); //核审
        jsonObject.put("hq",""); //核签
        jsonObject.put("wjrq",""); //文件日期
        jsonObject.put("hqbm",""); //会签部门
        jsonObject.put("ldps",""); //领导批示
        jsonObject.put("zbbm",""); //主办部门

        jsonObject.put("field1",""); //预留字段 1  用于传输 flowId
        jsonObject.put("field2",""); //预留字段 2  用于传输 runId
        jsonObject.put("field3",""); //预留字段 3  用于传输 runName
        jsonObject.put("field4",""); //预留字段 4  用于传输 prcsId
        jsonObject.put("field5",""); //预留字段 5  用于传输 flowPrcs
        for (Map<String, Object> datum : data) {
            switch (datum.get("key").toString()) {
                case "DATA_2":
                    jsonObject.put("bt", datum.get("value").toString());//标题
                    break;
                case "DATA_4":
                    break;
                case "DATA_15":
                    break;
                case "DATA_20":
                    break;
                case "DATA_32":
                    jsonObject.put("mj",datum.get("value").toString());
                    break;
                case "DATA_25":
                    break;
                case "DATA_28":
                    break;
                case "DATA_35":
                    jsonObject.put("jh",datum.get("value").toString());
                    break;
                case "DATA_26":
                    break;
                case "DATA_30":
                    jsonObject.put("wjrq",datum.get("value").toString());
                    jsonObject.put("bwrq",datum.get("value").toString());
                    break;
                case "DATA_31":
                    break;
                case "DATA_36":
                    jsonObject.put("wh",datum.get("value").toString());
                    break;
                case "DATA_37":
                    jsonObject.put("hqbm",datum.get("value").toString()); //会签部门
                    break;
                case "DATA_38":
                    break;
                case "DATA_39":
                    break;
                case "DATA_41":
                    break;
                case "DATA_63":
                    break;
                case "DATA_64":
                    break;
                case "DATA_42":
                    break;
                case "DATA_44":
                    break;
                case "DATA_45":
                    break;
                case "DATA_65":
                    break;
                case "DATA_66":
                    break;
                case "DATA_47":
                    break;
                case "DATA_67":
                    break;
                case "DATA_68":
                    break;
                case "DATA_53":
                    break;
                case "DATA_58":
                    break;
                case "DATA_59":
                    break;
                case "DATA_56":
                    break;
                case "DATA_61":
                    break;
                case "DATA_62":
                    break;
                case "DATA_48":
                    break;


            }
        }

    return jsonObject.toJSONString();
    }




    public int crateDoc(String file,String fileName) throws IOException {
        DocServiceLocator docServiceLocator = new DocServiceLocator();

        try {
            //根据Eclipse生成的Web Service客户端程序，取得接口
            DocServicePortType service = docServiceLocator.getDocServiceHttpPort(new URL(GdPara.url));
            String session = service.login(GdPara.u, GdPara.p,0, GdPara.ip);
            //System.out.println(session);


            DocInfo info  = new DocInfo();


            DocAttachment[] attachment = new DocAttachment[1];

            FileInputStream fis = new FileInputStream(file);//创建流通道


            byte[] b = new byte[1024*8];

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //System.out.println("开始");
            int len = 0;
            while ((len = fis.read(b)) != -1){//从文件中读取字节保存到b数组中，读到文件末尾返回-1

                out.write(b,0,b.length); //将指定字节数组中从偏移量 0 开始的 len 个字节写入此字节数组输出流。
                out.flush();

            }
            //System.out.println("结束");

            byte[] bytes = out.toByteArray();

            fis.close();
            out.close();

            //附件
            attachment[0] = new DocAttachment();
            attachment[0].setDocid(0);
            attachment[0].setImagefileid(0);
            attachment[0].setFilecontent(Base64.encode(bytes));
            attachment[0].setFilename(fileName);
            attachment[0].setIszip(1);


            //info.setSeccategory(Integer.parseInt(fileDirectory));//文档子目录
            //info.setDoccreaterid(Integer.parseInt(user_id));//文档最后修改者
            //info.setOwnerid(Integer.parseInt(user_id));//文档拥有者

            info.setId(0);
            info.setSeccategory(57);
            info.setDocSubject(fileName);//文档标题
            //info.setDoccontent("文档内容写什么好呢?"); //文档内容 HTML格式
            info.setDoccreatedate(DateFormat.getDatestr(new Date()));// 文档创建日期
            info.setAttachments(new DocAttachment[]{attachment[0]});//设置此DocInfo的附件值
            int docId = service.createDoc(info, session);
            //System.out.println("创建的文档的docid："+docId);

            return docId;



        } catch (ServiceException e) {

            e.printStackTrace();
        }
        return 0;
    }

}
